from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import Optional, List
import logging

# 导入问答模型
from apps.utils.neo4j.chatbot_graph import ChatBotGraph  # 假设chatbot_graph.py在同一目录下
from datetime import  datetime
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建路由实例
neo4j = APIRouter()

# 初始化问答机器人
try:
    chat_bot = ChatBotGraph()
    logger.info("Neo4j问答机器人初始化成功")
except Exception as e:
    logger.error(f"Neo4j问答机器人初始化失败: {str(e)}")
    chat_bot = None


# 请求模型
class QuestionRequest(BaseModel):
    question: str
    user_id: Optional[str] = None  # 可选的用户ID，用于追踪不同用户的查询


# 响应模型
class AnswerResponse(BaseModel):
    question: str
    answer: str
    success: bool = True
    message: Optional[str] = None


@neo4j.post("/query", response_model=AnswerResponse, summary="Neo4j知识图谱问答")
async def query_neo4j(request: QuestionRequest):
    """
    通过Neo4j知识图谱进行问答

    - 接收用户问题，返回基于知识图谱的回答
    - 如果问答机器人初始化失败，返回500错误
    - 如果问题为空，返回400错误
    """
    # 检查问答机器人是否初始化成功
    if not chat_bot:
        raise HTTPException(
            status_code=500,
            detail="Neo4j问答机器人初始化失败，请检查服务配置"
        )

    # 检查问题是否为空
    if not request.question.strip():
        raise HTTPException(
            status_code=400,
            detail="问题不能为空，请输入有效的查询内容"
        )

    try:
        # 记录查询日志
        logger.info(f"用户查询: {request.question} (用户ID: {request.user_id or '未知'})")

        # 获取回答
        answer = chat_bot.chat_main(request.question)

        # 返回结果
        return AnswerResponse(
            question=request.question,
            answer=answer
        )
    except Exception as e:
        # 记录错误日志
        logger.error(f"查询处理失败: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail=f"处理查询时发生错误: {str(e)}"
        )


@neo4j.get("/health", summary="检查Neo4j问答服务健康状态")
async def check_health():
    """检查Neo4j问答服务是否正常运行"""
    if chat_bot:
        return {
            "status": "healthy",
            "message": "Neo4j问答服务运行正常",
            "timestamp": datetime.now().isoformat()
        }
    else:
        return {
            "status": "unhealthy",
            "message": "Neo4j问答服务初始化失败",
            "timestamp": datetime.now().isoformat()
        }
